package tools

import (
	"strings"
	"time"
)

const CAPTCHA = "captcha:"

type RedisStore struct{}

//设置captcha
func (r RedisStore) Set(id string, value string) error {
	ri, err := NewRedisInstance()
	if err != nil {
		return err
	}
	return ri.RedisDBClient.Set(ctx, CAPTCHA+id, value, time.Minute*5).Err()
}

//获取captcha
func (r RedisStore) Get(id string, clear bool) string {
	ri, err := NewRedisInstance()
	if err != nil {
		return ""
	}
	value, err := ri.RedisDBClient.Get(ctx, CAPTCHA+id).Result()
	if err != nil {
		return ""
	}

	if clear {
		err = ri.RedisDBClient.Del(ctx, CAPTCHA+id).Err()
		if err != nil {
			return ""
		}
	}

	return value
}

//验证captcha
func (r RedisStore) Verify(id, answer string, clear bool) bool {
	value := RedisStore{}.Get(id, clear)
	value = strings.ToUpper(value)
	answer = strings.ToUpper(answer)
	return value == answer
}
